const Router = require('koa-router');
const axios = require('axios');
const cheerio = require('cheerio');
const log4js = require('log4js');
const logger = log4js.getLogger();
const db = require('../db');
const bcrypt = require('bcrypt');

const router = new Router({
    prefix: '/api/crawler'
});

// uu898接口
router.get('/uu898', async (ctx) => {
    logger.info('GET /api/crawler/uu898 请求');
    try {
        const url = 'https://www.uu898.com/newTrade-95-c-3-2325-s25023/';
        logger.info(`请求目标URL: ${url}`);
        const { data: html } = await axios.get(url, {
            headers: {
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36'
            }
        });
        const $ = cheerio.load(html);
        const result = [];
        // 遍历每个商品
        $('#divCommodityLst .splb_list').each((i, el) => {
            const priceStr = $(el).find('.Red.zuan_dh span').first().text().trim();
            const unit = $(el).find('.sp_li1 h6 span').first().text().trim();
            const price = parseFloat(priceStr);
            // 提取unit中的=xxxx万金数字
            let unitValue = null;
            const match = unit.match(/=([\d.]+)万金/);
            if (match) {
                unitValue = parseFloat(match[1]);
            }
            // 过滤空和小于20的
            if (!isNaN(price) && price >= 20 && !isNaN(unitValue)) {
                const totalGold = parseFloat((unitValue * price).toFixed(2));
                result.push({ price, unit, unitValue, totalGold });
            }
        });
        // 按unitValue升序排序
        result.sort((a, b) => b.unitValue - a.unitValue);
        logger.info(`返回数据数量: ${result.length}`);
        ctx.body = {
            success: true,
            count: result.length,
            data: result
        };
    } catch (err) {
        logger.error('uu898接口出错:', err);
        ctx.body = {
            success: false,
            error: err.message
        };
    }
});

// 新增：爬取dd373 good-list-box下的数据，单价和比例按新规则
router.get('/dd373', async (ctx) => {
    logger.info('GET /api/crawler/dd373 请求');
    try {
        const url = 'https://www.dd373.com/s-rbg22w-c-42hcun-fuv0cp-8699kc-0-0-0.html';
        logger.info(`请求目标URL: ${url}`);
        const { data: html } = await axios.get(url, {
            headers: {
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36'
            }
        });
        // console.log('html = ', html)
        const $ = cheerio.load(html);
        const result = [];
        // good-list-box下的每个商品
        $('.good-list-box .goods-list-item').each((i, el) => {
            // 单价
            const priceStr = $(el).find('.goods-price.game-currency-price > span').first().text().replace(/[^\d.]/g, '').trim();
            const price = parseFloat(priceStr);
            // 比例
            const unit = $(el).find('.width233 .font12.colorFF5').first().text().trim();
            // 提取unitValue
            let unitValue = null;
            const match = unit.match(/=([\d.]+)万金币/);
            if (match) {
                unitValue = parseFloat(match[1]);
            }
            // 总金币数
            let totalGold = null;
            if (!isNaN(price) && !isNaN(unitValue)) {
                totalGold = parseFloat((unitValue * price).toFixed(2));
            }
            if (!isNaN(price) && price >= 20 && !isNaN(unitValue)) {
                result.push({ price, unit, unitValue, totalGold });
            }
        });
        // 按unitValue升序排序
        result.sort((a, b) => b.unitValue - a.unitValue);
        logger.info(`返回数据数量: ${result.length}`);
        ctx.body = {
            success: true,
            count: result.length,
            data: result
        };
    } catch (err) {
        logger.error('dd373接口出错:', err);
        ctx.body = {
            success: false,
            error: err.message
        };
    }
});

// 用户注册接口
router.post('/register', async (ctx) => {
    const { username, phone, password, avatar } = ctx.request.body;
    if (!username || !phone || !password) {
        ctx.body = { success: false, message: '用户名、手机号和密码为必填项' };
        return;
    }
    try {
        // 检查用户名或手机号是否已存在
        const [users] = await db.query('SELECT id FROM user WHERE username = ? OR phone = ?', [username, phone]);
        if (users.length > 0) {
            ctx.body = { success: false, message: '用户名或手机号已存在' };
            return;
        }
        // 密码加密
        const hash = await bcrypt.hash(password, 10);
        // 插入新用户
        await db.query(
            'INSERT INTO user (username, phone, password, avatar) VALUES (?, ?, ?, ?)',
            [username, phone, hash, avatar || null]
        );
        ctx.body = { success: true, message: '注册成功' };
    } catch (err) {
        ctx.body = { success: false, message: err.message };
    }
});

// 数据库测试接口
router.get('/test-db', async (ctx) => {
    try {
        const [rows] = await db.query('SELECT NOW() as now');
        ctx.body = {
            success: true,
            data: rows
        };
    } catch (err) {
        ctx.body = {
            success: false,
            message: err.message
        };
    }
});

module.exports = router; 